import {login} from '@/api/users'
import {getInfo} from "../../api/users";
import {getName, setName} from "../../utils/storage";
import moment from 'moment';

const state = {
  token: '',
  name: '',
  role_id: '',
  avtor: '',
  time: ''
  // user_id: ''
};
const mutations = {
  SET_TOKEN: (state, payload) => {
    state.token = payload;
  },
  SET_NAME: (state, payload) => {
    state.name = payload;
  },
  SET_ROLE_ID: (state, payload) => {
    state.role_id = payload;
  },
  SET_AVTOR: (state, payload) => {
    state.avtor = payload;
  },
  SET_TIME: (state, payload) => {
    state.time = payload;
  },
};
const actions = {// rootState 可以获取另外一个modules的数据
  login({commit}, payload) {
    return new Promise((resolve, reject) => {
      // 异步操作  payload:{username:'admin' ,password:'admin'}
      login(payload).then(res => {
        let {token, role_id, username} = res;
        commit('SET_TOKEN', token);
        commit('SET_TIME', moment(new Date()).format('YYYY-MM-dd HH:mm'));
        setName(username);
        // commit('SET_ROLE_ID', role_id);
        resolve(res);
      })
    })
  },

  getInfo({commit}) {
    return new Promise((resolve, reject) => {
      // 异步操作  payload:{username:'admin' ,password:'admin'}
      getInfo(getName()).then(res => {
        let {role_id} = res;
        commit('SET_ROLE_ID', role_id);
        resolve(res);
      })
    })
  }
};

export default {
  state, mutations, actions, namespaced: true//命名空间
}

